package com.github.binarywang.demo.wx.miniapp.utils;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaSubscribeMessage;
import cn.hutool.core.date.DateUtil;
import com.github.binarywang.demo.wx.miniapp.model.WxMessageEntity;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 微信推送服务提醒公用方法
 *
 */
@Slf4j
@Component
public class WxPushUtil {
    @Resource
    private WxMaService wxService;

    /**
     * 跳转的小程序页面
     */
    private static final String PAGES_ZP = "pages/home/home";

    /**
     * 模板ID
     */
    @Value("${wx.xcx.templateIdSqtz}")
    String FCW_TEMPLATE_ID;

    /**
     * 微信服务通知发送
     * @param openIds
     * @param msg
     */
    public String sendSmallMsg(List<String> openIds, WxMessageEntity msg) {
        Map<String, String> map = new HashMap<>();
        map.put("thing1","");
        map.put("thing2","");
        map.put("date3", DateUtil.now());
        map.put("thing4","");

        try{
            for (String openId : openIds){
                WxMaSubscribeMessage wxMaSubscribeMessage = WxMaSubscribeMessage.builder()
                    .toUser(openId)
                    .templateId(FCW_TEMPLATE_ID)
                    .page(PAGES_ZP)
                    .build();
                // 设置将推送的消息
                map.forEach((k, v) -> {
                    wxMaSubscribeMessage.addData(new WxMaSubscribeMessage.MsgData(k, v));
                });
                wxService.getMsgService().sendSubscribeMsg(wxMaSubscribeMessage);
            }
            return "";
        }catch (WxErrorException e){
            log.info(e.getMessage());
            return "";
        }
    }


}
